package org.example.graalvmdemo.service.impl;

import org.example.graalvmdemo.model.User;
import org.example.graalvmdemo.service.UserService;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

@Service
@ImportRuntimeHints(UserServiceImpl.UserServiceRuntimeHints.class)
public class UserServiceImpl implements UserService {

    @Override
    public String getUserById(Long id) {
        String name = "";
        try {
            Method getTestName = User.class.getMethod("getTestName");

            name = (String) getTestName.invoke(User.class.newInstance());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
        return name;
    }

    @Override
    public String getWelcomeMessage() {
        // 读取资源文件
        Properties props = new Properties();
        try (InputStream is = getClass().getResourceAsStream("/static/messages.properties")) {
            props.load(is);
            return props.getProperty("welcome", "Default Welcome");
        } catch (IOException e) {
            return "Error loading message";
        }
    }
    static class UserServiceRuntimeHints implements RuntimeHintsRegistrar {

        @Override
        public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
            hints.resources().registerPattern("static/*");
            try {
                hints.reflection().registerConstructor(User.class.getConstructor(),  ExecutableMode.INVOKE);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
    }


}